package com.yangye.piconfig.config;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.authentication.CachingUserDetailsService;
import org.springframework.security.core.userdetails.UserCache;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.cache.EhCacheBasedUserCache;

import java.lang.reflect.Constructor;

/**
 * @author yangye
 * @date 2019/8/28
 */
@Configuration
public class UserDetailsCacheConfig {

	@Autowired
	@Qualifier("piUserDetailsServiceImpl")
	private UserDetailsService userDetailsService;

	@Autowired
	private CacheManager cacheManager;

	@Bean
	public UserCache userCache() {
		try {
			EhCacheBasedUserCache userCache = new EhCacheBasedUserCache();
			Cache cache = cacheManager.getCache("userCache");
			userCache.setCache(cache);
			return userCache;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@Bean
	public UserDetailsService userDetailsService() {
		Constructor constructor = null;
		try {
			constructor = CachingUserDetailsService.class.getDeclaredConstructor(UserDetailsService.class);
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		}
		constructor.setAccessible(true);
		CachingUserDetailsService cachingUserDetailsService = (CachingUserDetailsService) BeanUtils.instantiateClass(constructor, userDetailsService);
		cachingUserDetailsService.setUserCache(userCache());
		return cachingUserDetailsService;
	}
}
